package asia.yuanding.wechat.system.intercept;

import asia.yuanding.wechat.system.constant.HttpStatus;
import asia.yuanding.wechat.system.util.JwtUtil;
import asia.yuanding.wechat.system.util.R;
import asia.yuanding.wechat.system.util.ThreadUser;
import asia.yuanding.wechat.web.entity.User;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName: LoginIntercept
 * @Author: YuanDing
 * @Date: 2025/7/26 9:59
 * @Description:
 */


@Configuration
public class LoginIntercept implements HandlerInterceptor {

    @Resource
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        boolean blankIfStr = StrUtil.isBlankIfStr(token);

        // 校验通过，放行
        if (!blankIfStr && jwtUtil.verifyToken(token)) {
            ThreadUser.setUserInfo(jwtUtil.getUser(token));
            return true;
        }

        // 失败则拦截
        response.setStatus(HttpStatus.UNAUTHORIZED.getCode());
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(new JSONObject(R.fail(HttpStatus.UNAUTHORIZED.getCode() , HttpStatus.UNAUTHORIZED.getMessage())).toString().getBytes());
        outputStream.flush();
        outputStream.close();
        return false;
    }
}
